package org.grow.present.service;

import org.grow.present.dto.ChatMessage;
import org.grow.present.exception.MissTargetException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.*;

/**
 * @Author: xwg
 * @CreateDate: 2025/9/19
 */


@Component
public class ChatWebSocketHandler extends TextWebSocketHandler {
    private static final List<WebSocketSession> sessions = Collections.synchronizedList(new ArrayList<>());
    private static final Map<String, String> users = Collections.synchronizedMap(new HashMap<>());

    private static JwtService jwtService;

    @Autowired
    public void setJwtService(JwtService jwtService) {
        ChatWebSocketHandler.jwtService = jwtService;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
//        HttpHeaders handshakeHeaders = session.getHandshakeHeaders();
//        System.out.println(handshakeHeaders);
//        System.out.println(session.getUri());
        String query = session.getUri().getQuery();
        if (query != null) {
            if (!query.contains("token")) {
                System.out.println("当前聊天登录人无法核对真实信息，应该拒绝连接");
            }
            String token = query.replace("token=", "");
            Map<String, Object> map = jwtService.parseToken(token);
            String uid = (String) map.get("UID");
            System.out.println("uid real  " + uid);
//            users.put(session.getId(), uid);
//            broadcastSystemMessage(uid + " 真实加入了聊天室");
        }

        System.out.println("New connection: " + session.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        ChatMessage chatMessage = ChatMessage.fromJson(payload);

        switch (chatMessage.getType()) {
            case "JOIN":
                System.out.println(session.getId() + chatMessage.getSender());
                users.put(session.getId(), chatMessage.getSender());
                broadcastSystemMessage(chatMessage.getSender() + " 加入了聊天室");
                break;
            case "CHAT":
                System.out.println("=-----==" + chatMessage + "----" + users);
                broadcastMessage(chatMessage);
                break;
            case "LEAVE":
                users.remove(session.getId());
                broadcastSystemMessage(chatMessage.getSender() + " 离开了聊天室");
                break;
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String username = users.get(session.getId());
        if (username != null) {
            broadcastSystemMessage(username + " 离开了聊天室");
            users.remove(session.getId());
        }
        sessions.remove(session);
        System.out.println("Connection closed: " + session.getId());
    }

    private void broadcastMessage(ChatMessage message) {
        String jsonMessage = message.toJson();
        synchronized (sessions) {
            for (WebSocketSession session : sessions) {
                try {
                    if (session.isOpen()) {
                        session.sendMessage(new TextMessage(jsonMessage));
                    }
                } catch (IOException e) {
                    System.err.println("Error sending message to session " + session.getId() + ": " + e.getMessage());
                }
            }
        }
    }

    private void broadcastSystemMessage(String content) {
        ChatMessage systemMessage = new ChatMessage("SYSTEM", content, "System");
        broadcastMessage(systemMessage);
    }
}